package com.example.dao;

import com.example.model.Question;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class QuestionDAO {
    private DataSource dataSource;

    public QuestionDAO() throws NamingException, SQLException {
        Context context = new InitialContext();
        dataSource = (DataSource) context.lookup("java:comp/env/jdbc/dev_community");
    }

    // 添加新问题
    public void addQuestion(Question question) throws SQLException {
        String query = "INSERT INTO questions (user_id, title, content) VALUES (?, ?, ?)";
        try (Connection conn = dataSource.getConnection();
             PreparedStatement stmt = conn.prepareStatement(query)) {
            stmt.setInt(1, question.getUserId());
            stmt.setString(2, question.getTitle());
            stmt.setString(3, question.getContent());
            stmt.executeUpdate();
        }
    }

    // 根据ID获取问题
    public Question getQuestionById(int id) throws SQLException {
        Question question = null;
        String query = "SELECT q.*, u.username AS author FROM questions q LEFT JOIN users u ON q.user_id = u.id WHERE q.id = ?";
        try (Connection conn = dataSource.getConnection();
             PreparedStatement stmt = conn.prepareStatement(query)) {
            stmt.setInt(1, id);
            ResultSet rs = stmt.executeQuery();
            if (rs.next()) {
                question = new Question();
                question.setId(rs.getInt("id"));
                question.setUserId(rs.getInt("user_id"));
                question.setTitle(rs.getString("title"));
                question.setContent(rs.getString("content"));
                question.setAuthor(rs.getString("author"));
                question.setCreateTime(rs.getTimestamp("created_at"));
                question.setViewCount(rs.getInt("view_count"));
                question.setCommentCount(getCommentCount(id));
            }
        }
        return question;
    }

    // 获取所有问题
    public List<Question> getAllQuestions() throws SQLException {
        List<Question> questions = new ArrayList<>();
        String query = "SELECT q.*, u.username AS author FROM questions q LEFT JOIN users u ON q.user_id = u.id ORDER BY q.created_at DESC";
        try (Connection conn = dataSource.getConnection();
             PreparedStatement stmt = conn.prepareStatement(query);
             ResultSet rs = stmt.executeQuery()) {
            while (rs.next()) {
                Question question = new Question();
                question.setId(rs.getInt("id"));
                question.setUserId(rs.getInt("user_id"));
                question.setTitle(rs.getString("title"));
                question.setContent(rs.getString("content"));
                question.setAuthor(rs.getString("author"));
                question.setCreateTime(rs.getTimestamp("created_at"));
                question.setViewCount(rs.getInt("view_count"));
                question.setCommentCount(getCommentCount(rs.getInt("id")));
                questions.add(question);
            }
        }
        return questions;
    }

    // 更新浏览次数
    public void incrementViewCount(int questionId) throws SQLException {
        String query = "UPDATE questions SET view_count = view_count + 1 WHERE id = ?";
        try (Connection conn = dataSource.getConnection();
             PreparedStatement stmt = conn.prepareStatement(query)) {
            stmt.setInt(1, questionId);
            stmt.executeUpdate();
        }
    }

    // 获取评论数量
    private int getCommentCount(int questionId) throws SQLException {
        String query = "SELECT COUNT(*) AS comment_count FROM answers WHERE question_id = ?";
        try (Connection conn = dataSource.getConnection();
             PreparedStatement stmt = conn.prepareStatement(query)) {
            stmt.setInt(1, questionId);
            ResultSet rs = stmt.executeQuery();
            if (rs.next()) {
                return rs.getInt("comment_count");
            }
        }
        return 0;
    }
}